package com.ylbh.modules.comment.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.binarywang.java.emoji.EmojiConverter;
import com.ylbh.common.pojo.comment.dto.EvaluateClassDTO;
import com.ylbh.common.pojo.comment.dto.EvaluateClassListDTO;
import com.ylbh.common.pojo.comment.dto.ShoppingCommentReplyDTO;
import com.ylbh.common.pojo.comment.dto.ShoppingGoodsCommentDTO;
import com.ylbh.common.pojo.comment.vo.*;
import com.ylbh.common.pojo.goods.vo.ShoppingGoodsCommentVO;
import com.ylbh.common.utils.*;
import com.ylbh.common.utils.IdWorker;
import com.ylbh.common.utils.TaoBaoUtils;
import com.ylbh.modules.comment.mapper.CommentMapper;
import com.ylbh.modules.comment.service.CommentService;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.junit.Assert;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;


@Service("commentService")
public class CommentServiceImpl extends ServiceImpl<CommentMapper, ShoppingGoodsCommentDTO> implements CommentService {
    @Autowired
    CommentMapper commentMapper;

    private EmojiConverter emojiConverter = EmojiConverter.getInstance();

    @Value("${url.commentImg}")
    private String commentImg;

    @Value("${url.commentVideo")
    private String commentVideoDir;

    /**
     * 根据商品id添加采集评论
     * @param shoppingGoodsCommentList
     * @param goodsId
     */
    @Override
    public void addCommentByGoodId(List<ShoppingGoodsCommentDTO> shoppingGoodsCommentList, Integer goodsId) {
        shoppingGoodsCommentList.forEach(shoppingGoodsCommentDTO -> {
            shoppingGoodsCommentDTO.setGoodsId(goodsId);
            shoppingGoodsCommentDTO.setState("1");
            // 评论来源  0为自主评论 1为淘宝
            shoppingGoodsCommentDTO.setCommentSrc("1");
            // 评论审核状态 0:待审核1:审核通过2:审核拒绝
            shoppingGoodsCommentDTO.setAuditStatus("1");
            String imgs[] = new String[shoppingGoodsCommentDTO.getCommentImages().length];
            for (int i = 0; i < shoppingGoodsCommentDTO.getCommentImages().length; i++) {
//                if (!shoppingGoodsCommentDTO.getCommentImages()[i].contains("https://") || !shoppingGoodsCommentDTO.getCommentImages()[i].contains("http://")) {
//                    String img = shoppingGoodsCommentDTO.getCommentImages()[i].replace("//", "http://");
//                    imgs[i] = img;
//                } else {
//                    imgs[i] = shoppingGoodsCommentDTO.getCommentImages()[i];
//                }

                String[] img = shoppingGoodsCommentDTO.getCommentImages()[i].split("//");
                imgs[i] = "http://" + img[1];
            }
            shoppingGoodsCommentDTO.setCommentImages(imgs);
//            for (String img : shoppingGoodsCommentDTO.getCommentImages()) {
//                img.replace("//", "http://");
//                i
//            }
//            String[] split = shoppingGoodsCommentDTO.getHeadImg().split("//");
//            shoppingGoodsCommentDTO.setHeadImg("http://" + split[1]);
            shoppingGoodsCommentDTO.setHeadImg(randomHead());

            // 过滤图片
//            filterPictures(shoppingGoodsCommentDTO);
            shoppingGoodsCommentDTO.setCommentId(new IdWorker().nextId());
            shoppingGoodsCommentDTO.setCommentImagesStr(StringUtils.join(shoppingGoodsCommentDTO.getCommentImages(),","));
            shoppingGoodsCommentDTO.setCommentVideosStr(StringUtils.join(shoppingGoodsCommentDTO.getCommentVideos(),","));
            if (!StringUtils.isEmpty(shoppingGoodsCommentDTO.getContent())) {
//                shoppingGoodsCommentDTO.setContent(emojiConverter.toAlias(shoppingGoodsCommentDTO.getContent()));
                shoppingGoodsCommentDTO.setContent(filterEmoji(emojiConverter.toAlias(shoppingGoodsCommentDTO.getContent())));
            } else {
                shoppingGoodsCommentDTO.setContent(null);
            }
            if (!StringUtils.isEmpty(shoppingGoodsCommentDTO.getGoodsDetail()))
                shoppingGoodsCommentDTO.setGoodsDetail(shoppingGoodsCommentDTO.getGoodsDetail().replace("&nbsp;&nbsp","  "));
            shoppingGoodsCommentDTO.setOrderId(IdWorker.getNoId().toString());
            save(shoppingGoodsCommentDTO);
        });
    }

    /**
     * 随机获取头像图片地址
     * @return
     */
    public static String randomHead(){
        String[] s = {"男", "女", "动漫男", "动漫女"};
        Random r = new Random();
        HashMap<String, String> map = new HashMap<>();
        map.put("sort", s[r.nextInt(4)]);
        map.put("format", "json");
        String s1 = null;
        try {
            s1 = HttpUtils.sendPost("https://api.uomg.com/api/rand.avatar", map, "utf-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
        com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(s1);
        return jsonObject.getString("imgurl");
    }

    public static void main(String[] args) throws Exception {
        String s = randomHead();
        com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(s);
        String imgurl = jsonObject.getString("imgurl");
        System.out.println(s);
    }


    /**
     * 过滤掉jar包未编译的表情
     * @param source
     * @return
     */
    public static String filterEmoji(String source) {
        if (StringUtils.isBlank(source)) {
            return source;
        }
        StringBuilder buf = null;
        int len = source.length();
        for (int i = 0; i < len; i++) {
            char codePoint = source.charAt(i);
            if (isEmojiCharacter(codePoint)) {
                if (buf == null) {
                    buf = new StringBuilder(source.length());
                }
                buf.append(codePoint);
            }
        }
        if (buf == null) {
            return source;
        } else {
            if (buf.length() == len) {
                buf = null;
                return source;
            } else {
                return buf.toString();
            }
        }
    }

    private static boolean isEmojiCharacter(char codePoint) {
        return (codePoint == 0x0) || (codePoint == 0x9) || (codePoint == 0xA)
                || (codePoint == 0xD)
                || ((codePoint >= 0x20) && (codePoint <= 0xD7FF))
                || ((codePoint >= 0xE000) && (codePoint <= 0xFFFD))
                || ((codePoint >= 0x10000) && (codePoint <= 0x10FFFF));
    }

    /**
     * 过滤图片
     * @param shoppingGoodsCommentDTO
     */
    private void filterPictures (CommentJson shoppingGoodsCommentDTO){
        String refererUrl = shoppingGoodsCommentDTO.getRefererUrl();
        // 头像
        String headImg = shoppingGoodsCommentDTO.getHeadImg();
        if(StringUtils.isNotBlank(headImg)){
            // 上传图片到oss
            shoppingGoodsCommentDTO.setHeadImg(TaoBaoUtils.uploadFile(headImg, refererUrl, commentImg));
        } else {
          // 填充默认头像
            shoppingGoodsCommentDTO.setHeadImg("");
        }

        // 评论图片
        if (null != shoppingGoodsCommentDTO.getImg()) {
            String[] commentImages = shoppingGoodsCommentDTO.getImg();
            for (int i = 0; i < commentImages.length; i++) {
                String commentImage = commentImages[i];

                if (StringUtils.isNotBlank(commentImage)) {
                    // 替换图片尺寸
                    commentImage = commentImage.replace("width=40", "width=90");
                    commentImage = commentImage.replace("height=40", "height=90");
                    // oss
                    commentImages[i] = TaoBaoUtils.uploadFile(commentImage.replaceAll("\"", ""), refererUrl, commentImg);
                }
            }
            shoppingGoodsCommentDTO.setImg(commentImages);
        }

        if (!StringUtils.isEmpty(shoppingGoodsCommentDTO.getCommentVideos()) && !"[]".equals(shoppingGoodsCommentDTO.getCommentVideos())) {
            String[] commentVideos = shoppingGoodsCommentDTO.getCommentVideos().replace("[", "").replace("]", "").split(",");
            if (null != commentVideos && commentVideos.length > 0) {
                for (int i = 0; i < commentVideos.length; i++) {
                    String commentVideo = commentVideos[i];

                    if (StringUtils.isNotBlank(commentVideo)) {
                        // oss
                        commentVideos[i] = TaoBaoUtils.uploadFile(commentVideo, refererUrl, commentVideoDir);
                    }
                }
            }
            shoppingGoodsCommentDTO.setVideo(commentVideos);
        }

    }

    /**
     * 商城评论列表
     * @param pageDTO
     * @return
     */
    @Override
    public PageUtils queryCommentList(EvaluateClassListDTO pageDTO) {
        Page<Integer> page = new Page<>(pageDTO.getPage(), pageDTO.getLimit());
        List<ShoppingGoodsCommentDTO> list = commentMapper.selectCommentList(pageDTO, page);
//        for (ShoppingGoodsCommentDTO dto:list) {
//            if (!StringUtils.isEmpty(dto.getCommentImagesStr())) {
//                dto.setCommentImages(dto.getCommentImagesStr().split(","));
//            }
//            if (!StringUtils.isEmpty(dto.getCommentVideosStr())) {
//                dto.setCommentVideos(dto.getCommentVideosStr().split(","));
//            }
//        }
        return new PageUtils(new Page<ShoppingGoodsCommentDTO>().setTotal(page.getTotal()).setRecords(list));
    }

    /**
     * 评论审核
     * @param id
     * @param statusType
     */
    @Override
    public void modifyAuditStatusById(List<Long> id, Integer statusType) {
        commentMapper.updateAuditStatusById(id, statusType);
    }

    /**
     * 删除评论
     * @param ids
     */
    @Override
    public void removeCommentById(List<Long> ids) {
        commentMapper.deleteCommentById(ids);
    }

    /**
     * 评论回复列表
     * @param commentId
     * @return
     */
    @Override
    public CommentReplyListVO getCommentReplyListById(String commentId) {
        // 查询出购买商品的首评论人
        CommentReplyListVO vo = commentMapper.selectCommentReplyListById(commentId);
        // 查出对应所有回复评论的人
        List<CommentReplyPersonalVO> personal = commentMapper.selectCommentReplyPersonalById(commentId);
        for (CommentReplyPersonalVO personalVO : personal) {
            if (!StringUtils.isEmpty(personalVO.getParentId())) {
                CommentReplyPersonalVO reply = commentMapper.selectReplyById(personalVO.getParentId());
                if (null != reply) {
                    personalVO.setUserId(reply.getUserId());
                    personalVO.setRealName(reply.getRealName());
                    personalVO.setHeadImg(reply.getHeadImg());
                }
            } else {
                personalVO.setUserId(vo.getUserId());
                personalVO.setRealName(vo.getRealName());
                personalVO.setHeadImg(vo.getHeadImg());
            }
        }
        vo.setReply(personal);
        if (!StringUtils.isEmpty(vo.getCommentImages())) {
            String[] imgs = vo.getCommentImages().split(",");
            vo.setImg(imgs);
        }
        if (!StringUtils.isEmpty(vo.getCommentVideos())) {
            String[] video = vo.getCommentVideos().split(",");
            vo.setVideo(video);
        }
        return vo;
    }

    /**
     * 回复评论提交
     * @param dto
     */
    @Override
    public void addCommentReply(ShoppingCommentReplyDTO dto) {
        // 如果评论人id和追问人id都不为空，则追回回复,获取父id
        dto.setId(new IdWorker().nextId());
        dto.setDate(new Date());
        if (!StringUtils.isEmpty(dto.getCommentId()) && !StringUtils.isEmpty(dto.getReplyId())) {
            String[] conent = dto.getContent().split(" ");
            if (conent.length >= 2) {
                dto.setContent(conent[1]);
            }
            commentMapper.insertCommentReplyPersonal(dto);
        } else {
            // 则是客服直接直接回复评价人
            commentMapper.insertCommentReply(dto);
        }
    }

    /**
     * 评价标签列表
     * @param dto
     * @return
     */
    @Override
    public PageUtils queryEvaluateClassList(EvaluateClassListDTO dto) {
        Page<Integer> page = new Page<>(dto.getPage(), dto.getLimit());
        List<EvaluateClassListVO> list = commentMapper.selectEvaluateClassList(dto, page);
        return new PageUtils(new Page<EvaluateClassListVO>().setTotal(page.getTotal()).setRecords(list));
    }

    /**
     * 获取标签详情
     * @param evaluateId
     * @return
     */
    @Override
    public EvaluateClassListVO getEvaluateClassDetailsById(Integer evaluateId) {
        return commentMapper.selectEvaluateClassDetailsById(evaluateId);
    }

    /**
     * 修改评价标签
     * @param dto
     */
    @Override
    public void modifyEvaluateClassById(EvaluateClassDTO dto) {
        commentMapper.updateEvaluateClassById(dto);
    }

    /**
     * 新增评价标签
     * @param dto
     */
    @Override
    public void addEvaluateClass(EvaluateClassDTO dto) {
        dto.setCreateTime(new Date());
        dto.setCreateUserId(ShiroUtils.getUserId());
        commentMapper.insertEvaluateClass(dto);
    }

    /**
     * 删除评价标签
     * @param ids
     */
    @Override
    public void removeEvaluateClassById(Integer ids) {
        commentMapper.deleteEvaluateClassById(ids);
    }

    /**
     * 回复审核
     * @param asList
     * @param statusType
     */
    @Override
    public void modifyAuditReplyById(List<Long> asList, Integer statusType) {
        commentMapper.updateAuditReplyById(asList, statusType);
    }

    /**
     * 根据id来采集评论接口
     * @param id
     */
    @Override
    public List<ShoppingGoodsCommentDTO> getGoodsComments(String id, Integer numberOfBars, Integer dataPage) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("id", id);
        map.put("page", dataPage);
        map.put("page_size", numberOfBars);
        map.put("tag_id", null);
        map.put("sort", "all");
        String s = HttpClientHelperUtils.sendHttpPostEs("http://www.shihuo.cn/sports/getGoodsComments", map);
        JSONObject jsonObject = JSONObject.fromObject(s);
        JSONObject data = JSONObject.fromObject(jsonObject.get("data"));
        List<CommentToJsonVO> toList = FastJsonUtil.toList(data.get("comment").toString(), CommentToJsonVO.class);
        ArrayList<ShoppingGoodsCommentDTO> list = new ArrayList<>();
        if (null != toList) {
            for (CommentToJsonVO vo : toList) {
                ShoppingGoodsCommentDTO commentVO = new ShoppingGoodsCommentDTO();
                commentVO.setCommentImages(vo.getImg_attr());
                commentVO.setContent(vo.getContent());
                commentVO.setCreateTime(vo.getCreated_at());
                commentVO.setHeadImg(vo.getAvatar());
                commentVO.setRealName(vo.getNickname());
                list.add(commentVO);
            }
        }
        return list;
    }

    /**
     * 将评论添加到定时评论表
     * @param shoppingGoodsCommentDTO
     * @param goodsId
     */
    @Override
    public void addTimingComment(List<ShoppingGoodsCommentDTO> shoppingGoodsCommentDTO, Integer goodsId) {
        if (null != goodsId && shoppingGoodsCommentDTO.size() > 0) {
            for (ShoppingGoodsCommentDTO dto:shoppingGoodsCommentDTO){
                if (!StringUtils.isEmpty(dto.getContent())) {
                    dto.setContent(filterEmoji(emojiConverter.toAlias(dto.getContent())));
                }
            }
            commentMapper.insertTimingComment(JSON.toJSON(shoppingGoodsCommentDTO).toString(), goodsId, ShiroUtils.getUserId(), new Date());
        }
    }

    @Override
    public void commentTask() {
        // 查询出要执行的评论信息
        List<TimingCommentVO> list = commentMapper.selectTimingComment();
        if (list.size() > 0) {
            for (TimingCommentVO vo:list) {
                if (!StringUtils.isEmpty(vo.getCommentContent())) {
                    List<CommentJson> shoppingGoodsCommentList = FastJsonUtil.toList(vo.getCommentContent(), CommentJson.class);
                    for (CommentJson shoppingGoodsCommentDTO:shoppingGoodsCommentList) {
//                    shoppingGoodsCommentList.forEach(shoppingGoodsCommentDTO -> {
                        // 查询这条评论是否已经添加过
                        int isAdd = commentMapper.selectIsAddByGoodsId(shoppingGoodsCommentDTO.getRealName(), shoppingGoodsCommentDTO.getContent(), vo.getGoodsId());
                        if (isAdd == 0) {
                            shoppingGoodsCommentDTO.setGoodsId(vo.getGoodsId());
                            shoppingGoodsCommentDTO.setState("1");
                            // 评论来源  0为自主评论 1为淘宝
                            shoppingGoodsCommentDTO.setCommentSrc("1");
                            // 评论审核状态 0:待审核1:审核通过2:审核拒绝
                            shoppingGoodsCommentDTO.setAuditStatus("1");
                            if (!StringUtils.isEmpty(shoppingGoodsCommentDTO.getCommentImages()) && !"[]".equals(shoppingGoodsCommentDTO.getCommentImages())) {
                                String imgs[] = new String[shoppingGoodsCommentDTO.getCommentImages().replace("[", "").replace("]", "").split(",").length];
                                String[] s = shoppingGoodsCommentDTO.getCommentImages().replace("[", "").replace("]", "").split(",");
                                for (int i = 0; i < imgs.length; i++) {

                                    String[] img = s[i].split("//");
                                    imgs[i] = "http://" + img[1];
                                }
                                shoppingGoodsCommentDTO.setImg(imgs);
                            } else {
                                shoppingGoodsCommentDTO.setImg(null);
                            }

//                        shoppingGoodsCommentDTO.setHeadImg(randomHead());

                            // 过滤图片
                            filterPictures(shoppingGoodsCommentDTO);
                            shoppingGoodsCommentDTO.setCommentId(new IdWorker().nextId());
                            shoppingGoodsCommentDTO.setCommentImagesStr(StringUtils.join(shoppingGoodsCommentDTO.getImg(), ","));
                            shoppingGoodsCommentDTO.setCommentVideosStr(StringUtils.join(shoppingGoodsCommentDTO.getVideo(), ","));
                            if (!StringUtils.isEmpty(shoppingGoodsCommentDTO.getContent())) {
//                shoppingGoodsCommentDTO.setContent(emojiConverter.toAlias(shoppingGoodsCommentDTO.getContent()));
                                shoppingGoodsCommentDTO.setContent(filterEmoji(emojiConverter.toAlias(shoppingGoodsCommentDTO.getContent())));
                            } else {
                                shoppingGoodsCommentDTO.setContent(null);
                            }
                            if (!StringUtils.isEmpty(shoppingGoodsCommentDTO.getGoodsDetail()))
                                shoppingGoodsCommentDTO.setGoodsDetail(shoppingGoodsCommentDTO.getGoodsDetail().replace("&nbsp;&nbsp", "  "));
                            shoppingGoodsCommentDTO.setOrderId(IdWorker.getNoId().toString());
                            ShoppingGoodsCommentDTO dto = new ShoppingGoodsCommentDTO();
                            BeanUtils.copyProperties(shoppingGoodsCommentDTO, dto);
                            if (!StringUtils.isEmpty(dto.getRate()) && "-1".equals(dto.getRate())) {
                                dto.setRate("0");
                            }
                            save(dto);
                        }
//                    });
                    }
                }
                // 根据Id修改为已执行
                commentMapper.updateTimingCommentStatueById(vo.getId(), new Date());
            }
        }
    }

    @Override
    public List<ShoppingGoodsCommentDTO> getGoodsCommentsById(String goodsCollectionId) {
        List<ShoppingGoodsCommentVO> commentList =commentMapper.selectCommentsById(goodsCollectionId);
        ArrayList<ShoppingGoodsCommentDTO> arrayList = new ArrayList<>();
        if (null != commentList) {
            for (ShoppingGoodsCommentVO vo : commentList) {
                ShoppingGoodsCommentDTO commentDTO  = new ShoppingGoodsCommentDTO();
                System.out.println(vo.getCommentImages());
                if (null != vo.getCommentImages()) {
                    String [] str = vo.getCommentImages().split(",");
                    for (int i = 0; i < str.length; i++) {
                        str[i] = "http://image.yilianbaihui.cn/consumer/"+ str[i];
                    }
                    commentDTO.setCommentImages(str);
                }
                commentDTO.setContent(vo.getContent());
                commentDTO.setHeadImg("http://image.yilianbaihui.cn/consumer/" + vo.getHeadImg());
                commentDTO.setRealName(vo.getRealName());
                commentDTO.setCreateTime(vo.getCreateTime());
                commentDTO.setUserId(vo.getUserId());
                arrayList.add(commentDTO);
            }
        }
        return arrayList;
    }

    @Override
    public void insertComment(List<ShoppingGoodsCommentDTO> shoppingGoodsCommentList, Integer goodsId) {
        if (null != goodsId && shoppingGoodsCommentList.size() > 0) {
            for (ShoppingGoodsCommentDTO dto:shoppingGoodsCommentList){
                ShoppingGoodsCommentVO vo = new ShoppingGoodsCommentVO();
                IdWorker idW = new IdWorker();
                if (!StringUtils.isEmpty(dto.getContent())) {
                    vo.setContent(filterEmoji(emojiConverter.toAlias(dto.getContent())));
                }
                if (dto.getHeadImg().length() > 0) {
                    String headIng = dto.getHeadImg().substring(dto.getHeadImg().lastIndexOf('/',dto.getHeadImg().lastIndexOf('/')-1) + 1);
                    vo.setHeadImg(headIng);
                }
                if (dto.getCommentImages().length > 0 && null != dto.getCommentImages()) {
                    for (int i = 0; i < dto.getCommentImages().length; i++) {
                        dto.getCommentImages()[i] = dto.getCommentImages()[i].substring(dto.getCommentImages()[i].lastIndexOf('/',dto.getCommentImages()[i].lastIndexOf('/') - 1) + 1);
                    }
                    String str = StringUtils.join(dto.getCommentImages(),",");
                    vo.setCommentImages(str);
                }
                vo.setAuditStatus("1");
                vo.setRealName(dto.getRealName());
                vo.setCommentId(idW.nextId());
                vo.setCreateTime(new Date());
                // 2代表送贝
                vo.setCommentSrc(2);
                commentMapper.insertComment(vo, goodsId);
            }
        }
    }
}
